#include "Animation.h"

Animation::Animation()
{
	this->frames.clear();
	this->delays.clear();
	this->active = false;
	this->currentframe = 0;
	this->lastupdate = 0;
	this->timer = new Timer();
	this->id = 0;
}

Animation::~Animation()
{
	this->frames.clear();
	this->delays.clear();
	this->active = false;
	this->currentframe = 0;
	this->lastupdate = 0;
	delete this->timer;
	this->id = 0;
}

bool Animation::PushFrame(TextureSection* frame, float delay)
{
	this->frames.push_back(frame);
	this->delays.push_back(delay);
	return true;
}

void Animation::Play()
{
	this->active = true;
	this->currentframe = 0;
	this->lastupdate = this->timer->GetTime();
}

void Animation::Pause()
{
	this->active = false;
}

void Animation::PlayPause()
{
	this->active = ! this->active;
}

void Animation::Update()
{
	if(! this->active )
		return;

	if(( this->frames.empty() ) || ( this->delays.empty()))
		return;

	if( this->currentframe == this->frames.size() - 1 )
	{
		if( this->lastupdate + this->delays[0] < this->timer->GetTime() )
		{
			this->currentframe = 0;
			this->lastupdate = this->timer->GetTime();
		}
	}
	else
	{
		if( this->lastupdate + this->delays[this->currentframe + 1] < this->timer->GetTime() )
		{
			this->currentframe ++;
			this->lastupdate = this->timer->GetTime();
		}
	}
}

bool Animation::DrawAnimation(int X, int Y, GLfloat Scale, GLfloat Rotation, GLfloat red, GLfloat green, GLfloat blue)
{
	if( this->frames.empty() || this->delays.empty() || ( this->currentframe >= this->frames.size() ))
		return false;
	return this->frames[this->currentframe]->DrawTextureSection(X,Y,Scale,Rotation,red,green,blue);
}

unsigned int Animation::GetId()
{
	return this->id;
}

unsigned int Animation::SetId( unsigned int new_id)
{
	return this->id = new_id;
}